package com.mall.service.authority.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.autoconfig.interceptor.BaseContext;
import com.mall.commons.common.CommonResult;
import com.mall.commons.utils.JwtUtils;
import com.mall.model.domain.UmsAdmin;
import com.mall.model.domain.UmsAdminRoleRelation;
import com.mall.model.domain.UmsMenu;
import com.mall.model.domain.UmsRole;
import com.mall.model.vo.PageResult;
import com.mall.model.vo.UmsInfoVo;
import com.mall.service.authority.service.UmsAdminRoleRelationService;
import com.mall.service.authority.service.UmsAdminService;
import com.mall.service.authority.service.UmsMenuService;
import com.mall.service.authority.service.UmsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class UmsAdminController {

    @Autowired
    private UmsAdminService umsAdminService;

    @Autowired
    private UmsMenuService umsMenuService;

    @Autowired
    private UmsRoleService umsRoleService;

    @Autowired
    private UmsAdminRoleRelationService umsAdminRoleRelationService;

    /**
     * 登录
     *
     * @param umsAdmin
     * @return
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody UmsAdmin umsAdmin) {

        String password = umsAdmin.getPassword();
        String username = umsAdmin.getUsername();
//        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        LambdaQueryWrapper<UmsAdmin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdmin::getUsername, username);

        UmsAdmin user = umsAdminService.getOne(queryWrapper);
        String pwd = user.getPassword();
        if (password.equals(pwd)) {
            HashMap<String, Long> map = new HashMap<>();
            map.put("id", user.getId());

            String token = JwtUtils.getToken(map);
            HashMap<String, String> tokenMap = new HashMap<>();
            tokenMap.put("tokenHead", "Bearer ");
            tokenMap.put("token", token);
            return CommonResult.success(tokenMap);
        }

        return CommonResult.error("登录失败,用户不存在或者密码错误");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/logout")
    public CommonResult logout() {
        BaseContext.remove();
        return CommonResult.success("退出成功");
    }

    /**
     * 获取用户消息
     *
     * @param name
     * @return
     */
    @GetMapping("/info")
    public CommonResult info(String name) {
        UmsInfoVo vo = new UmsInfoVo();
        vo.setUsername(name);
        String currentId = BaseContext.getCurrentId();
        UmsAdmin user = umsAdminService.getById(currentId);

        vo.setRoles(user.getNote());

        List<UmsMenu> list = umsMenuService.list();
        vo.setIcon(user.getIcon());
        vo.setMenus(list);
        return CommonResult.success(vo);
    }

    /**
     * 用户列表
     *
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @GetMapping("list")
    public CommonResult list(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize, String keyword) {

        PageResult pr = umsAdminService.getList(pageNum, pageSize, keyword);

        return CommonResult.success(pr);
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable("id") Integer userId) {
        umsAdminService.removeById(userId);
        //删除对应的角色关系表
        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdminRoleRelation::getAdminId,userId);
        umsAdminRoleRelationService.remove(queryWrapper);
        return CommonResult.success("删除成功");
    }

    /**
     * 修改用户
     *
     * @param userId
     * @param user
     * @return
     */
    @PostMapping("/update/{id}")
    public CommonResult update(@PathVariable("id") Integer userId, @RequestBody UmsAdmin user) {
        umsAdminService.updateById(user);
        return CommonResult.success("修改成功");
    }

    /**
     * 用户注册
     *
     * @param umsAdmin
     * @return
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody UmsAdmin umsAdmin) {
        umsAdminService.save(umsAdmin);
        return CommonResult.success("注册成功");
    }

    /**
     * 根据id获取用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable("id") Integer userId) {
        UmsAdmin user = umsAdminService.getById(userId);
        return CommonResult.success(user);
    }

    /**
     * 修改账号状态
     *
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/updateStatus/{id}")
    public CommonResult updateStatus(@PathVariable("id") Integer id, Integer status) {
        UmsAdmin umsAdmin = umsAdminService.getById(id);
        umsAdmin.setStatus(status);
        umsAdminService.updateById(umsAdmin);
        return CommonResult.success(null);
    }

    /**
     * 根据id查询角色信息
     * @param id
     * @return
     */
    @GetMapping("/role/{adminId}")
    public CommonResult role(@PathVariable("adminId") Integer id) {
        List<UmsRole> list= umsRoleService.getByAdminId(id);
        return CommonResult.success(list);
    }

    /**
     * 给用户分配角色
     * @param adminId
     * @param roleIds
     * @return
     */
    @PostMapping("/role/update")
    public CommonResult roleUpdate(Integer adminId,@RequestParam List<Integer> roleIds){
        umsAdminRoleRelationService.roleUpdate(adminId,roleIds);
        return CommonResult.success(null);
    }
}
